<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addFormVisible = true">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="广告名称" value="1"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok"/>
      </div>
    </div>

    <!-- table -->
    <el-table stripe style="width: 100%" :data="tableData" :key="key" border fit highlight-current-row ref="tableDataRef">
      <el-table-column v-if="colData[0].istrue" min-width="140" align="center" prop="advert_id" label="id">
      </el-table-column>
<!--      <el-table-column v-if="colData[1].istrue" min-width="120" align="center" prop="content" label="广告内容图">-->
<!--        <template slot-scope="scope">-->
<!--          <el-image  style="width: 80px; height: 80px"  :src="scope.row.content" fit="fill"></el-image>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column v-if="colData[2].istrue" min-width="110" align="center" prop="name" label="广告名称">
      </el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="110" align="center" prop="content_type" label="类型">
        <template slot-scope="scope">
          <span v-if="scope.row.content_type==1">单图</span>
          <span v-else>轮播图</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[6].istrue" min-width="110" align="center" prop="admin_name" label="创建人">
      </el-table-column>
      <el-table-column v-if="colData[7].istrue" prop="create_time" label="更新时间" min-width="140" align="center">
        <template slot-scope="scope">{{scope.row.update_time| activateTime}}</template>
      </el-table-column>
      <el-table-column label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="editSelfAdvertOpen(scope.row)">编辑</el-button>
            <el-button size="mini" @click="getDelAdvert(scope.row.advert_id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
                     layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>

    <!-- 添加弹窗 -->
    <el-dialog title="广告内容管理" :visible.sync="addFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="40%"  @close="addFormclose">
      <el-form :model="addForm"  ref="ruleForm" :rules="rules" class="diolog_adapt">
        <el-form-item label="配置名称:" label-width="120px" prop="name">
          <el-input v-model="addForm.name" autocomplete="off" placeholder="请输入配置名称"></el-input>
        </el-form-item>
        <el-form-item label="类型" label-width="120px" prop="content_type">
          <el-select v-model="addForm.content_type" placeholder="请选择广告类型" style="flex:1">
            <el-option v-for="item in advertOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否可见:" label-width="120px" prop="is_show">
          <el-radio-group v-model="addForm.is_show">
            <el-radio :label=1>可见</el-radio>
            <el-radio :label=-1>不可见</el-radio>
          </el-radio-group>
        </el-form-item>
          <div v-for="(item,index) in adImageList" >
            <el-card>
              <el-form-item label="图片:" label-width="100px" prop="course_img">
                <el-upload
                  class="avatar-uploader"
                  action
                  :auto-upload="false"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :on-change="(res,file,type)=> {adImgUpload(res,file,item)}"
                >
                  <img v-if="item.img" :src="item.img" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="排序:" label-width="100px" v-show="addForm.content_type==2">
                <el-input v-model="item.sort" placeholder="请输入排序" type="number"></el-input>
              </el-form-item>
              <el-form-item label="跳转方式" label-width="100px">
                <el-select v-model="item.linkType" placeholder="请选择跳转方式" style="flex:1" @change="setTempOptions">
                  <el-option v-for="l in linkOptions" :key="l.value" :label="l.label"
                             :value="l.value.toString()"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="广告内容" label-width="100px" v-show="item.linkType!=5 && item.linkType!=''">
                <el-select v-model="item.keyId" placeholder="请选择app" style="flex:1" v-show="item.linkType==1">
                  <el-option v-for="l in appOptions" :key="l.value" :label="l.label"
                             :value="l.value.toString()"></el-option>
                </el-select>
                <el-select v-model="item.keyId" placeholder="请选择视频" style="flex:1" v-show="item.linkType==2">
                  <el-option v-for="l in videOptions" :key="l.value" :label="l.label"
                             :value="l.value.toString()"></el-option>
                </el-select>
                <el-select v-model="item.keyId" placeholder="请选择音频" style="flex:1" v-show="item.linkType==3">
                  <el-option v-for="l in mp3Options" :key="l.value" :label="l.label"
                             :value="l.value.toString()"></el-option>
                </el-select>
                <el-select v-model="item.keyId" placeholder="请选择文档" style="flex:1" v-show="item.linkType==4">
                  <el-option v-for="l in docOptions" :key="l.value" :label="l.label"
                             :value="l.value.toString()"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="链接地址:" label-width="100px" v-show="item.linkType==5">
                <el-input v-model="item.link" autocomplete="off" placeholder="请输入链接地址"></el-input>
              </el-form-item>
              <el-form-item label-width="100px" v-show="addForm.content_type==2">
                <el-button icon="el-icon-plus" type="primary" @click="toAddList"></el-button>
                <el-button icon="el-icon-minus" type="danger" @click="toRemoveList(item,index)"></el-button>
              </el-form-item>
            </el-card>
          </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" size="mini" round @click="editSelfContent('ruleForm')">确 定
        </el-button>
        <el-button v-else type="primary" @click="addSelfContent('ruleForm')" size="mini" round>确定</el-button>
      </div>
    </el-dialog>

    <!-- 删除弹窗start -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents"
                   :deleteText="deleteDialogs.deleteText"/>
    <!-- 删除弹窗end -->
  </div>
</template>

<script>
  import UploadExcelComponent from "@/components/UploadExcelSn/index.vue";
  import dynamicTable from "@/components/DynamicTable";
  import {getBatchTwo} from "@/api/equipment.js";
  import {addAdvertContent,queryAdvertData,editAdvertData,delAdvertData} from "@/api/launcherMade"
  import deleteDialog from "@/components/deleteDialog";
  import tableMini from '@/utils/tableMini.js'
  import {ossImage} from "@/utils/ossUpload";

  export default {
    mixins: [tableMini],
    components: {UploadExcelComponent, dynamicTable, deleteDialog},
    data() {
      return {
        checkboxVal: ["ID", "广告内容", "广告名称", "类型", "排序", "链接类型", "创建人", "更新时间"],
        tableData: [],
        select: "", //搜索条件
        //编辑按钮控制
        editSubjects: false,
        advertId: 0,
        listQuery: {
          startSize: 1,
          pageSize: 10,
          batch: undefined,
          username: undefined,
          userId: localStorage.getItem("ID")
        },
        addFormVisible: false,
        advertOptions: [{label: '单图', value: 1}, {label: '轮播图', value: 2}],
        linkOptions: [{label: 'App', value: 1}, {label: '视频', value: 2}, {label: '音频', value: 3},{label: '文档', value: 4}, {label: '网页地址',value: 5 }],
        handleOptions: [{label: '应用宝', value: 1}, {label: '微信', value: 2}],
        addForm: {
          content: '',
          name: '',
          content_type: '',
          is_show: 1,
        },
        rules: {
          name: [
            { required: true, message: '请输入配置名称', trigger: 'blur' },
          ],
          content_type: [
            { required: true, message: '请选择广告类型', trigger: 'change' }
          ],
        },
        adImageList: [{
          img: '',
          sort: '',
          linkType: '', //链接类型
          link: '', //链接
          keyId: '', //类型为app时候则为app_id，类型为课程是测试course_id
        }],
        appOptions: [], //app可选项
        videOptions: [], //视频可选项
        mp3Options: [], //音频可选项
        docOptions:[], //文档可选项
        tempOptions :[],
      }
    },
    created() {
      this.getAdvertTableData()
    },
    methods: {
      getDelAdvert(advertId){
        this.deleteDialogs.show = true
        this.deleteDialogs.deleteId = advertId
      },
      //删除按钮事件
      deleteEvents() {
        let params = {
          userId: localStorage.getItem("ID"),
          last_ip: sessionStorage.getItem("Ip"),
          advert_id: this.deleteDialogs.deleteId
        }
        delAdvertData(params).then(res => {
          if(res.code==200){
            this.$message.success(res.msg)
          }else{
            this.$message.error(res.msg)
          }
          this.getAdvertTableData()
        })
      },
      //搜索,1:模板名称，2：适配学龄段 3：批次
      idnameSearch() {
        if (!this.select) return this.$message.warning("请先选择查询条件");
        this.listQuery.startSize = 1
        this.listQuery.pageSize = 10
        switch (this.select) {
          case '1':
            this.listQuery.name = this.searchTable
            this.getAdvertTableData();
            break;
        }
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      //图片上传
      adImgUpload(res, file,item) {
        ossImage(res.raw,res.name).then(res => {//图片上传
          item.img = res
        }).catch(err => {
          this.$message.error("图标上传失败")
        })
      },

      //添加
      addSelfContent(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let addForm = JSON.parse(JSON.stringify(this.addForm))
            addForm.last_ip = sessionStorage.getItem("Ip")
            addForm.userId = localStorage.getItem("ID")
            addForm.content = JSON.parse(JSON.stringify(this.adImageList))
            addAdvertContent(addForm).then(res => {
              if(res.code==200){
                this.$message.success(res.msg)
                this.getAdvertTableData()
              }
              this.addFormVisible = false
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },
      toAddList() {
        this.adImageList.push({
          img: '',
          sort: '',
          linkType: '', //链接类型
          link: '', //链接
          keyId: ''
        })
      },
      toRemoveList(item,index){
        if (this.adImageList.length == 1) {
          this.$message.error('请至少条少一张广告图片~')
          return
        }
        let tempList = this.adImageList
        tempList.map((value, i) => {
          if ( i== index) {
            tempList.splice(index, 1);
            this.adImageList = tempList;
          }
        });

      },
      setTempOptions(event) {
        if (event == 1) {
          this.tempOptions = this.appOptions;
        }
        if (event == 2) {
          this.tempOptions = this.contentOptions;
        }
      },

      editSelfAdvertOpen(row) {
        this.addFormVisible=true
        this.editSubjects=true
        this.addForm=row
        this.adImageList=row.adImageList
      },
      //编辑信息
      editSelfContent(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let editForm = JSON.parse(JSON.stringify(this.addForm))
            editForm.last_ip = sessionStorage.getItem("Ip")
            editForm.userId = localStorage.getItem("ID")
            editForm.content = JSON.parse(JSON.stringify(this.adImageList))
            editAdvertData(editForm).then(res => {
              this.$message.success(res.msg)
              this.getAdvertTableData()
              this.addFormVisible = false
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },

      getAdvertTableData() {
          queryAdvertData(this.listQuery).then(res => {
            if(res.code==200){
              this.tableData = res.data
              this.total = res.total
              this.appOptions = res.otherData.appOptions
              this.videOptions = res.otherData.videOptions
              this.mp3Options = res.otherData.mp3Options
              this.docOptions = res.otherData.docOptions
            }else{
              this.$message.error(this.res.msg)
            }
        }).catch(err => {
          this.tableData = []
          this.total = 0
        })
      },

      //编辑添加表单关闭事件
      addFormclose() {
        this.editSubjects=false
        this.$nextTick(() => {
          this.$refs.ruleForm.resetFields();
          this.addForm = this.$options.data().addForm
          this.adImageList = [{
            img: '',
            sort: '',
            linkType: '', //链接类型
            link: '', //链接
            keyId: '', //类型为app时候则为app_id，类型为课程是测试course_id
          }]
        })
      },
      Refresh(){
        this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), name: undefined}
        this.getAdvertTableData()
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
    }
  }
</script>
<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }
  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
</style>
